package com.maxvision.mybatis.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.maxvision.mybatis.service.IExcelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;

/**
 * 类说明
 *
 * @author HuangRongFu
 * @date 2022/12/28
 */
@RestController
@RequestMapping("/excel")
@Log4j2
public class ExcelController {
    
    @Autowired
    private IExcelService excelService;
    
    @PostMapping
    public ResponseEntity readExcel(@RequestParam MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith("xlsx") && !originalFilename.endsWith("xls")){
            
            return new ResponseEntity("请上传xls/xlsx格式文件", HttpStatus.BAD_REQUEST);
        }

        return excelService.readExcel(file);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) {
        
        String fileName = "employee.xlsx";
        File file = new File("src/main/resources/file/人员批量导入模板.xls");
        try {

            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-disposition","attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            OutputStream outputStream = response.getOutputStream();

            outputStream.write(FileUtil.readBytes(file));
            outputStream.flush();
            outputStream.close();
            
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
    }
}
